package config

import (
	"os/user"
	"path"
	"time"
)

var LoginInfo = &Login{}

type Login struct {
	Host                 string
	Port                 int
	User                 string
	Password             string
	Key                  string
	KeyPassphrase        string
	BastionHost          string
	BastionPort          int
	BastionUser          string
	BastionPassword      string
	BastionKey           string
	BastionKeyPassphrase string
	ConnectTimeout       time.Duration
}

func (l *Login) Parse() error {
	// 获取运行用户
	if l.User == "" {
		currenUser, err := user.Current()
		if err != nil {
			return err
		}
		l.User = currenUser.Username
	}
	// 读取ssh key
	if l.Password == "" {
		if l.Key == "~/.ssh/id_rsa" {
			currenUser, err := user.Current()
			if err != nil {
				return err
			}
			l.Key = path.Join(currenUser.HomeDir, ".ssh/id_rsa")
		}
		key, err := readSSHKey(l.Key)
		if err != nil {
			return err
		}
		l.Key = key
	} else {
		l.Key = ""
	}
	// 如果不存在跳板机
	if l.BastionHost == "" {
		return nil
	}
	if l.BastionUser == "" {
		l.BastionUser = l.User
	}
	if l.BastionPassword == "" {
		if l.BastionKey == "~/.ssh/id_rsa" {
			currenUser, err := user.Current()
			if err != nil {
				return err
			}
			l.BastionKey = path.Join(currenUser.HomeDir, ".ssh/id_rsa")
		}
		key, err := readSSHKey(l.BastionKey)
		if err != nil {
			return err
		}
		l.BastionKey = key
	} else {
		l.BastionKey = ""
	}

	return nil
}
